// 采用pinia 管理用户数据，但是页面已刷新就会丢失，因为存在内存中，因此需要配合 localStorage保存使用

import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import type { IAuth, IUserInfo } from '@/biz/repo/user'
import { useLocalStorage } from '@/biz/hooks/useLocalStorage'

const getDefaultUserInfo: () => IUserInfo = () => ({
  id: '',
  avatar: 'https://b.yzcdn.cn/vant/icon-demo-1126.png',
  nickname: '请登录'
})

// 用户管理状态
export const useUserStore = defineStore('user', () => {
  //localstorage
  //给返回的值赋值变量-用户数据
  const {
    value: $userInfo,
    setValue: $setUserInfoValue,
    removeValue: $removeUserInfo
  } = useLocalStorage('userInfo', getDefaultUserInfo())

  // token 数据
  const { setValue: $setTokenValue, removeValue: $removeTokenItem } = useLocalStorage('token', '')

  const state = ref({
    userInfo: getDefaultUserInfo(),
    token: ''
  })

  const getUserInfo = computed(() => {
    //判断pinia store里有没有数据
    if (!state.value.userInfo || !state.value.userInfo.id) {
      state.value.userInfo = $userInfo.value
    }
    return state.value.userInfo
  })

  const setUserInfo = ({ token, userInfo }: IAuth) => {
    state.value.userInfo = userInfo
    state.value.token = token
    $setUserInfoValue(userInfo)
    $setTokenValue(token)
  }

  const removeUserInfo = () => {
    state.value.userInfo = getDefaultUserInfo()
    state.value.token = ''
    $removeUserInfo()
    $removeTokenItem()
  }

  return {
    state, //存放的数据
    getUserInfo, //获取信息
    setUserInfo, //设置信息
    removeUserInfo //移除信息
  }
})
